package com.lanyou.cook.web.userManagement;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.pentaho.di.core.encryption.Encr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.lanyou.cook.common.Constants;
import com.lanyou.cook.datadictionary.UserEnableType;
import com.lanyou.cook.datadictionary.UserLogOpt;
import com.lanyou.cook.entity.domain.FieldSystem;
import com.lanyou.cook.entity.domain.userManagement.Organization;
import com.lanyou.cook.entity.domain.userManagement.Role;
import com.lanyou.cook.entity.domain.userManagement.User;
import com.lanyou.cook.entitylistener.domain.UserEntityListenerForKettleObject;
import com.lanyou.cook.importdata.vo.ResponseBean;
import com.lanyou.cook.paramsetting.ParamSettingService;
import com.lanyou.cook.repository.FieldSystemRepository;
import com.lanyou.cook.repository.userManagement.OrganizationRepository;
import com.lanyou.cook.repository.userManagement.RoleRepository;
import com.lanyou.cook.repository.userManagement.UserRepository;
import com.lanyou.cook.service.SendEmailService;
import com.lanyou.cook.service.UserLogService;
import com.lanyou.cook.service.security.UserSessionService;
import com.lanyou.cook.util.DateUtil;
import com.lanyou.cook.util.RSAUtil;
import com.lanyou.cook.util.RandomUtil;
import com.lanyou.cook.web.param.UserParam;
import com.lanyou.esb.servicemix.util.FtpRouteHandleUtil;

import jdk.nashorn.internal.runtime.linker.LinkerCallSite;

/**
 * 用户管理相关业务的控制层
 * 
 * @author 杨晨睿
 *
 */
@RestController
@RequestMapping(Constants.BASE_URL_API + "/users")
public class UserController {

	@Autowired
	private OrganizationRepository organizationRepository;

	@Autowired
	private RoleRepository roleRepository;

	@Autowired
	ParamSettingService paramSettingService;

	@Autowired
	private FieldSystemRepository fieldSystemRepository;

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private UserLogService userLogService;

	@Autowired
	private UserSessionService userSessionService;
	
	@Autowired
	private SendEmailService sendEmailService;

	/**
	 * 查询特定条件下的用户集合
	 * 
	 * @param param
	 *            类型:UserParam 待查询的用户参数实体
	 * @param pageable
	 *            类型:Pageable 待查询的分页参数实体
	 * @return 带条件和分页查询出的用户集合
	 */
	
	@RequestMapping("/search/findByExample")
	@RequiresPermissions(value = { "userManagement" })
	public Page<User> findByExample(UserParam param,
			Pageable pageable) {
	
		Specification<User> spec = new Specification<User>() {
			@Override
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicatesList = new ArrayList<>();

				// 账号
				if (StringUtils.isNotBlank(param.getUserCode())) {
					predicatesList.add(cb.like(root.get("userCode"), '%' + param.getUserCode() + '%'));
				}

				// 所属公司
				if (StringUtils.isNotBlank(param.getCompanyId())) {
					predicatesList
							.add(cb.equal(root.get("organization").get("parent").get("id"), param.getCompanyId()));
				}

				// 所属部门
				if (StringUtils.isNotBlank(param.getOrgId())) {
					predicatesList.add(cb.equal(root.get("organization").get("id"), param.getOrgId()));
				}

				// 所属角色
				if (StringUtils.isNotBlank(param.getRoleId())) {
					predicatesList.add(cb.equal(root.get("role").get("id"), param.getRoleId()));
				}

				// 用户名称
				if (StringUtils.isNotBlank(param.getUserName())) {
					predicatesList.add(cb.like(root.get("userName"), '%' + param.getUserName() + '%'));
				}

				// 邮箱地址
				if (StringUtils.isNotBlank(param.getEmailAddress())) {
					predicatesList.add(cb.like(root.get("emailAddress"), '%' + param.getEmailAddress() + '%'));
				}
				// 电话号码
				if (StringUtils.isNotBlank(param.getPhoneNumber())) {
					predicatesList.add(cb.like(root.get("phoneNumber"), '%' + param.getPhoneNumber() + '%'));
				}

				// 授权状态
				if (StringUtils.isNotBlank(param.getGrantStatus())) {
					switch (param.getGrantStatus()) {
					case "authorized":
						predicatesList.add(cb.isNotNull(root.get("role").get("id")));
						break;
					case "unAuthorized":
						predicatesList.add(cb.isNull(root.get("role").get("id")));
					}
				}
				// 纠正错误的时间参数
				DynaBean fixedDates = DateUtil.fixBeginTimeAndEndTime(param.getBeginOfCreateTime(),
						param.getEndOfCreateTime());
				Date fixedBeginTime = (Date) fixedDates.get("begin");
				Date fixedEndTime = (Date) fixedDates.get("end");

				Path<Date> pathDate = root.get("createTime");
				predicatesList.add(cb.or(cb.isNull(pathDate), cb.between(pathDate, fixedBeginTime, fixedEndTime)));

				query.where(predicatesList.toArray(new Predicate[predicatesList.size()]));
				return null;
			}
		};
		return userRepository.findAll(spec, pageable);
	}

	/**
	 * 用户注册时判断用户是否已经存在
	 * 
	 * @param userCode

	 *            +
	 *            类型:String 待注册的用户账号
	 * @return 类型:boolean 判断后返回的结果(存在返回true,不存在返回false)
	 */
	private boolean checkUserExists(String userCode) {
		User user = userRepository.findByUserCode(userCode);
		if (user != null) {
			return false;
		} else {
			return true;
		}
	}
	/**
	 * 用户注册
	 * 
	 * @param userParam
	 *            类型:UserParam 待注册的参数实体
	 * @return 类型:String 注册返回的结果(注册成功返回true,注册不成功返回相对应的错误描述)
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value = "/registeredUser", produces = "application/json", method = RequestMethod.POST)
	@Transactional
	public String registeredUser(@RequestBody UserParam userParam) throws UnsupportedEncodingException {
		JsonObject result = new JsonObject();
		if (!checkUserExists(userParam.getUserCode())) {
			result.addProperty("backValue", "用户账名已存在!");
			return result.toString();
		}
		User user = new User();

		if (userParam.getOrgId() != null) {
			Organization organization = organizationRepository.findOne(userParam.getOrgId());

			if (organization != null) {
				user.setOrganization(organization);
			}
		} else {
			result.addProperty("backValue", "公司和部门不能为空！");
			return result.toString();

		}

		if (userParam.getUserCode() != null) {
			user.setUserCode(userParam.getUserCode());
		} else {
			result.addProperty("backValue", "账号不能为空！");
			return result.toString();
		}
		if (userParam.getUserName() != null) {
			user.setUserName(userParam.getUserName());
		} else {
			result.addProperty("backValue", "姓名不能为空！");
			return result.toString();
		}

		if (userParam.getPassword() != null) {
			String password = "";
			try {
				// 进行RSA解密
				password = RSAUtil.decryptByPrivateKey(userParam.getPassword(), Constants.PRIVATE_KEY_BASE64);
			} catch (Exception e) {

			}
			user.setPassword(password);
		} else {
			result.addProperty("backValue", "密码不能为空！");
			return result.toString();
		}

		if (userParam.getEmpNo() != null) {
			user.setEmpNo(userParam.getEmpNo());
		}

		if (userParam.getPhoneNumber() != null) {
			user.setPhoneNumber(userParam.getPhoneNumber());
		}

		if (userParam.getEmailAddress() != null) {
			user.setEmailAddress(userParam.getEmailAddress());
		}
		
		user.setLoginStatus(UserEnableType.Disable.ValueCode);
		Map<String, String> map = new HashMap<String, String>();
		try{
			map.put("emailAddress", user.getEmailAddress());
			map.put("userCode", user.getUserCode());
			//用户注册时给用户发送邮件
			sendEmailService.CookSendEmail(map, Constants.USER_REGISTER_SUBJECT, Constants.USER_REGISTER_TEMPLATE);
		}catch(Exception e){
			e.printStackTrace();
		}
		map.put("company", user.getCompanyName());
		map.put("department", user.getDeptName());
		map.put("userName", user.getUserName());
		map.put("empNumber", user.getEmpNo());
		map.put("phoneNumber", user.getPhoneNumber());
		String requestIpAndPort = FtpRouteHandleUtil.getLocalHost();
		SimpleDateFormat DateTimeFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
		String time = DateTimeFormat.format(new Date()).replace(" ", "#");
		String requestUrl = "http://"+requestIpAndPort+"/pages/UserManagement/UserLogin.html?time=" + time;
		map.put("requestUrl", requestUrl);
		map.put("emailAddressForTemplate", user.getEmailAddress());
		User adminUser = userRepository.findByUserCode(Constants.FIXED_USER_CODE_FOR_ADMIN);
		map.put("emailAddress", adminUser.getEmailAddress());
		try {
			//用户注册时给接口管理员和管理员发送邮件
			sendEmailService.CookSendEmail(map, Constants.USER_REGISTER_VERIFY_SUBJECT,
					Constants.USER_REGISTER_VERIFY_TEMPLATE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<User> ifAdminUserList = userRepository.findByRole_Id(Constants.FIXED_ROLE_ID_FOR_IF_ADMIN);
		for (int i = 0; i < ifAdminUserList.size(); i++) {
			if (StringUtils.isNotBlank(ifAdminUserList.get(i).getEmailAddress())) {
				map.put("emailAddress", ifAdminUserList.get(i).getEmailAddress());
				try {
					sendEmailService.CookSendEmail(map, Constants.USER_REGISTER_VERIFY_SUBJECT,
							Constants.USER_REGISTER_VERIFY_TEMPLATE);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		UserEntityListenerForKettleObject.setKettleUser(user);
		userRepository.save(Arrays.asList(user));
		result.addProperty("backValue", true);
		userLogService.save(UserLogOpt.UserRegister, null, String.format("用户%s注册了", user.getUserName()));
		return result.toString();
	}
	/**
	 * 判断旧密码是否正确
	 * 
	 * @param userParam
	 *            类型:UserParam 待判断的参数实体
	 * @return 类型:boolean 判断后返回的结果(存在返回true,不存在返回false)
	 */
	private boolean checkOldPassword(@RequestBody UserParam userParam) {
		if (userParam.getOldPassword() == null) {
			return false;
		}
		User user = userSessionService.getCurrentAuthenticatedUser();
		String password = "";
		try {
			// 进行RSA解密

			password = RSAUtil.decryptByPrivateKey(userParam.getOldPassword(), Constants.PRIVATE_KEY_BASE64);
		} catch (Exception e) {

		}
		String encryptedPassword = Encr.encryptPasswordIfNotUsingVariables(password);
		if (StringUtils.equals(encryptedPassword, user.getPassword())) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 用户修改个人资料
	 * 
	 * @param userParam
	 *            类型:UserParam 待修改的用户参数实体
	 * @return 类型:String 用户修改返回的结果(修改成功返回true,修改不成功返回相对应的错误描述)
	 */
	@RequestMapping(value = "/updateUser", produces = "application/json", method = RequestMethod.POST)
	@Transactional
	public String updateUser(@RequestBody UserParam userParam) {
		JsonObject result = new JsonObject();
		if (userParam.getPassword() != null) {
			if (!checkOldPassword(userParam)) {
				result.addProperty("backValue", "旧密码不正确！");
				return result.toString();
			}
		}

		String userCode = UserSessionService.getCurrentAuthenticatedUserCode();
		User user = userRepository.findByUserCode(userCode);

		if (userParam.getOrgId() != null) {
			Organization organization = organizationRepository.findOne(userParam.getOrgId());

			if (organization != null) {
				user.setOrganization(organization);
			}
		}
		if (userParam.getRoleId() != null) {
			Role role = roleRepository.findOne(Role.idSpecification(userParam.getRoleId()));
			if (role != null) {
				user.setRole(role);
			}
		}

		if (userParam.getUserCode() != null) {
			if (!StringUtils.equals(user.getUserCode(), userParam.getUserCode())) {
				result.addProperty("backValue", "不能更改账号！");
				return result.toString();
			}
			// user.setUserCode(userParam.getUserCode());
		}
		if (userParam.getUserName() != null) {
			user.setUserName(userParam.getUserName());
		}

		if (userParam.getPassword() != null) {
			String password = "";
			try {
				// 进行RSA解密
				password = RSAUtil.decryptByPrivateKey(userParam.getPassword(), Constants.PRIVATE_KEY_BASE64);
			} catch (Exception e) {

			}
			user.setPassword(password);
		}

		if (userParam.getEmpNo() != null) {
			user.setEmpNo(userParam.getEmpNo());
		}

		if (userParam.getPhoneNumber() != null) {
			user.setPhoneNumber(userParam.getPhoneNumber());
		}

		if (userParam.getEmailAddress() != null) {
			user.setEmailAddress(userParam.getEmailAddress());
		}

		if (userParam.getLoginStatus() != null) {
			user.setLoginStatus(userParam.getLoginStatus());
		}

		if (userParam.getRemark() != null) {
			user.setRemark(userParam.getRemark());
		}

		UserEntityListenerForKettleObject.setKettleUser(user);
		userRepository.save(Arrays.asList(user));
		result.addProperty("backValue", true);
		userLogService.save(UserLogOpt.MaintenanceInformation, null,
				String.format("用户“%s”修改了个人的资料信息", user.getUserCode()));
		return result.toString();
	}

	/**
	 * 新增一个用户
	 * 
	 * @param userParam
	 *            类型:UserParam 待新增的参数实体
	 * @return 类型:String 注册返回的结果(新增成功返回true,新增不成功返回相对应的错误描述)
	 */
	@RequestMapping(value = "/administratorAddUser", produces = "application/json", method = RequestMethod.POST)
	@Transactional
	@RequiresPermissions(value = { "userManagement" })
	public String administratorAddUser(@RequestBody UserParam userParam) {
		JsonObject result = new JsonObject();
		if (!checkUserExists(userParam.getUserCode())) {
			result.addProperty("backValue", "用户名已存在!");
			return result.toString();
		}
		User user = new User();

		if (userParam.getOrgId() != null) {
			Organization organization = organizationRepository.findOne(userParam.getOrgId());

			if (organization != null) {
				user.setOrganization(organization);
			}
		}
		if (userParam.getRoleId() != null) {
			Role role = roleRepository.findOne(Role.idSpecification(userParam.getRoleId()));
			if (role != null) {
				user.setRole(role);
			}
		}
		
		if(StringUtils.equals(userParam.getRoleId(), Constants.FIXED_ROLE_ID_FOR_ADMIN)){
			List<FieldSystem> fieldSystems = fieldSystemRepository.findAll();
			Set<FieldSystem> fieldSystemSet = new HashSet<FieldSystem>();
			fieldSystemSet.addAll(fieldSystems);
			user.setFieldSystems(fieldSystemSet);
		}

		if (userParam.getUserCode() != null) {
			user.setUserCode(userParam.getUserCode());
		}
		if (userParam.getUserName() != null) {
			user.setUserName(userParam.getUserName());
		}

		if (userParam.getPassword() != null) {
			String password = "";
			try {
				// 进行RSA解密
				password = RSAUtil.decryptByPrivateKey(userParam.getPassword(), Constants.PRIVATE_KEY_BASE64);
			} catch (Exception e) {

			}
			user.setPassword(password);
		}

		if (userParam.getEmpNo() != null) {
			user.setEmpNo(userParam.getEmpNo());
		}

		if (userParam.getPhoneNumber() != null) {
			user.setPhoneNumber(userParam.getPhoneNumber());
		}

		if (userParam.getEmailAddress() != null) {
			user.setEmailAddress(userParam.getEmailAddress());
		}

		if (userParam.getLoginStatus() != null) {
			user.setLoginStatus(userParam.getLoginStatus());
		}

		if (userParam.getRemark() != null) {
			user.setRemark(userParam.getRemark());
		}
		
		if (userParam.getExeTimeOnDay() != null) {
			user.setExeTimeOnDay(userParam.getExeTimeOnDay());
		}

		UserEntityListenerForKettleObject.setKettleUser(user);
		userRepository.save(Arrays.asList(user));
		result.addProperty("backValue", true);
		userLogService.save(UserLogOpt.MaintenanceUser, null, String.format("新增了用户“%s”", user.getUserCode()));
		return result.toString();
	}

	@RequestMapping(value = "/startOrStopUserLoginStatus", produces = "application/json", method = RequestMethod.POST)
	@RequiresPermissions(value = { "userManagement" })
	@Transactional
	public String startOrStopUserLoginStatus(@RequestBody UserParam userParam) {
		JsonObject result = new JsonObject();
		User user = userRepository.findOne(User.idSpecification(userParam.getId()));
		if(checkIsCurrentUser(userParam)){
			result.addProperty("backValue", "不能启用/停用自己的账号！");
			return result.toString();
		}
		if(StringUtils.equals(user.getUserCode(), Constants.FIXED_USER_CODE_FOR_ADMIN)){
			result.addProperty("backValue", "不能启用/停用超级管理员admin的账号！");
			return result.toString();
		}

		if (userParam.getLoginStatus() != null) {
			user.setLoginStatus(userParam.getLoginStatus());
		}

		UserEntityListenerForKettleObject.setKettleUser(user);
		userRepository.save(Arrays.asList(user));
		result.addProperty("backValue", true);
		userLogService.save(UserLogOpt.MaintenanceUser, null, String.format("修改了用户“%s”", user.getUserCode()));
		return result.toString();
	}
	/**
	 * 修改用户个人资料
	 * 
	 * @param userParam
	 *            类型:UserParam 待修改的用户参数实体
	 * @return 类型:String 修改用户返回的结果(修改成功返回true,修改不成功返回相对应的错误描述)
	 */
	@RequestMapping(value = "/administratorUpdateUser", produces = "application/json", method = RequestMethod.POST)
	@RequiresPermissions(value = { "userManagement" })
	@Transactional
	public String administratorUpdateUser(@RequestBody UserParam userParam) {
		JsonObject result = new JsonObject();
		User user = userRepository.findOne(User.idSpecification(userParam.getId()));
		if(checkIsCurrentUser(userParam) && !StringUtils.equals(user.getLoginStatus(), userParam.getLoginStatus())){
			result.addProperty("backValue", "不能修改自己的登录限制！");
			return result.toString();
		}
		if(StringUtils.equals(user.getUserCode(), Constants.FIXED_USER_CODE_FOR_ADMIN)){
			result.addProperty("backValue", "不能修改超级管理员admin的相关信息！");
			return result.toString();
		}
		

		if (userParam.getOrgId() != null) {
			Organization organization = organizationRepository.findOne(userParam.getOrgId());

			if (organization != null) {
				user.setOrganization(organization);
			}
		}
		if (userParam.getRoleId() != null) {
			Role role = roleRepository.findOne(Role.idSpecification(userParam.getRoleId()));
			if (role != null) {
				user.setRole(role);
			}
		}

		if(StringUtils.equals(userParam.getRoleId(), Constants.FIXED_ROLE_ID_FOR_ADMIN)){
			List<FieldSystem> fieldSystems = fieldSystemRepository.findAll();
			if(Integer.parseInt(user.getFieldSystemCount()) > 0){
				user.getFieldSystems().clear();
			}
			user.getFieldSystems().addAll(fieldSystems);
		}
		
		if (userParam.getUserCode() != null) {
			if (!StringUtils.equals(user.getUserCode(), userParam.getUserCode())) {
				result.addProperty("backValue", "不能更改账号！");
				return result.toString();
			}
			// user.setUserCode(userParam.getUserCode());
		}
		if (userParam.getUserName() != null) {
			user.setUserName(userParam.getUserName());
		}

		if (userParam.getEmpNo() != null) {
			user.setEmpNo(userParam.getEmpNo());
		}

		if (userParam.getPhoneNumber() != null) {
			user.setPhoneNumber(userParam.getPhoneNumber());
		}

		if (userParam.getEmailAddress() != null) {
			user.setEmailAddress(userParam.getEmailAddress());
		}

		if (userParam.getLoginStatus() != null) {
			user.setLoginStatus(userParam.getLoginStatus());
		}

		if (userParam.getRemark() != null) {
			user.setRemark(userParam.getRemark());
		}
		
		if (userParam.getExeTimeOnDay() != null) {
			user.setExeTimeOnDay(userParam.getExeTimeOnDay());
		}
		
		if (userParam.getExeTimeOnDay() != null) {
			user.setExeTimeOnDay(userParam.getExeTimeOnDay());
		}

		UserEntityListenerForKettleObject.setKettleUser(user);
		userRepository.save(Arrays.asList(user));
		result.addProperty("backValue", true);
		userLogService.save(UserLogOpt.MaintenanceUser, null, String.format("修改了用户“%s”", user.getUserCode()));
		return result.toString();
	}

	/**
	 * 用户找回密码
	 * 
	 * @param userParam
	 *            类型:UserParam 待找回密码的用户参数实体
	 * @return 类型:String 用户找回密码返回的结果(成功找回密码返回true,找回密码失败返回相对应的错误描述)
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value = "/search/findBackPassword", produces = "application/json")
	@Transactional
	public String findBackPassword(@RequestBody UserParam userParam) throws UnsupportedEncodingException {
		JsonObject result = new JsonObject();
		User user = userRepository.findByUserCode(userParam.getUserCode());
		if (user != null) {
			if (!StringUtils.equals(user.getUserName(), userParam.getUserName())) {
				result.addProperty("backValue", "用户姓名不正确！");
				return result.toString();
			}
			if (!StringUtils.equals(user.getEmpNo(), userParam.getEmpNo())) {
				result.addProperty("backValue", "工号不正确！");
				return result.toString();
			}

			if (!StringUtils.equals(user.getEmailAddress(), userParam.getEmailAddress())) {
				result.addProperty("backValue", "邮箱地址不正确,请输入注册时使用的邮箱地址！");
				return result.toString();
			}

			try{
				//用户找回密码发送邮件
				String newPassword = RandomUtil.getRandomPwd(6);
				Map<String, String> map = new HashMap<String, String>();
				map.put("emailAddress", user.getEmailAddress());
				map.put("userCode", user.getUserCode());
				map.put("userPassword", newPassword);
				String requestIpAndPort = FtpRouteHandleUtil.getLocalHost();
				SimpleDateFormat DateTimeFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
				String time = DateTimeFormat.format(new Date()).replace(" ", "#");
				String requestUrl = "http://"+requestIpAndPort+"/pages/UserManagement/UserLogin.html?time=" + time;
				map.put("requestUrl", requestUrl);
				sendEmailService.CookSendEmail(map, Constants.USER_FIND_PASSWORD_BACK_SUBJECT, Constants.USER_FIND_PASSWORD_BACK_TEMPLATE);
				user.setPassword(newPassword);
			}catch(Exception e){
				e.printStackTrace();
			}
			
			
			UserEntityListenerForKettleObject.setKettleUser(user);
			userRepository.save(Arrays.asList(user));
			result.addProperty("backValue", true);
			userLogService.save(UserLogOpt.MaintenanceInformation, null,
					String.format("用户“%s”通过密码找回找回了密码", user.getUserCode()));
			return result.toString();
		} else {
			result.addProperty("backValue", "用户账号不存在！");
			return result.toString();
		}
	}

	/**
	 * 给用户分配角色和系统
	 * 
	 * @param userParam
	 *            类型:UserParam 待分配的用户参数实体
	 *            
	 *@return 类型:String 判断后返回的结果(存在返回true,不存在返回错误描述)
	 */
	@RequestMapping(value = "/assignRoleAndSystem", produces = "application/json", method = RequestMethod.POST)
	@RequiresPermissions(value = { "userRoleManagement" })
	@Transactional
	public String assignRoleAndSystems(@RequestBody UserParam userParam) {
		/*
		 * User user =
		 * userRepository.findOne(User.idSpecification(userParam.getId())); User
		 * currentUser = userSessionService.getCurrentAuthenticatedUser();
		 * JsonObject jo = new JsonObject(); if (userParam.getRoleId() != null)
		 * { Role role =
		 * roleRepository.findOne(Role.idSpecification(userParam.getRoleId()));
		 * if(user.getRole().getRoleName().equals("管理员")&&!role.getRoleName().
		 * equals("管理员")&&currentUser.getUserCode().equals(user.getUserCode())){
		 * jo.addProperty("backValue", "管理员不能更改自己的角色"); return jo.toString(); }
		 * if (role != null) { user.setRole(role); } }
		 */
		JsonObject jo = new JsonObject();
		User user = userRepository.findOne(User.idSpecification(userParam.getId()));
		if (userParam.getRoleId() != null) {
			Role role = roleRepository.findOne(Role.idSpecification(userParam.getRoleId()));
			if (role != null) {
				user.setRole(role);
			}
		}
		user.setLoginStatus(UserEnableType.Enable.ValueCode);
		if (userParam.getRemark() != null) {
			user.setRemark(userParam.getRemark());
		}

		if(StringUtils.equals(userParam.getRoleId(), Constants.FIXED_ROLE_ID_FOR_ADMIN)){
			List<FieldSystem> fieldSystems = fieldSystemRepository.findAll();
			if(Integer.parseInt(user.getFieldSystemCount()) > 0){
				user.getFieldSystems().clear();
			}
			user.getFieldSystems().addAll(fieldSystems);
		}else{
			Collection<String> fieldSystemIds = userParam.getFieldSystemIds();
			List<FieldSystem> fieldSystems = fieldSystemRepository.findAll(fieldSystemIds);
			user.getFieldSystems().clear();
			user.getFieldSystems().addAll(fieldSystems);
		}

		UserEntityListenerForKettleObject.setKettleUser(user);
		userRepository.save(Arrays.asList(user));
		userLogService.save(UserLogOpt.MaintenanceUser, null, String.format("给用户“%s”分配了角色和系统", user.getUserCode()));

		jo.addProperty("backValue", true);
		return jo.toString();
	}

	/**
	 * 删除前判断是否在操作当前用户
	 * 
	 * @param userParam
	 *            类型:UserParam 待判断的用户参数实体
	 * @return 类型:boolean 判断后返回的结果(存在返回true,不存在返回false) 
	 */
	private boolean checkIsCurrentUser(@RequestBody UserParam userParam) {
		String userCode = UserSessionService.getCurrentAuthenticatedUserCode();
		Long count = userRepository.countByUserCodeAndId(userCode, userParam.getId());
		if (count != 0) {
			return true;

		} else {
			return false;
		}
	}

	/**
	 * 删除一个用户
	 * 
	 * @param userParam
	 *            类型:UserParam 待删除的用户参数实体
	 * @return 类型:String 删除用户返回的结果(删除成功返回true,删除失败返回相对应的错误描述)
	 */
	@RequestMapping(value = "/deleteUser", produces = "application/json", method = RequestMethod.DELETE)
	@RequiresPermissions(value = { "userManagement" })
	@Transactional
	public String deleteUser(@RequestBody UserParam userParam) {
		JsonObject result = new JsonObject();
		User user = userRepository.findOne(User.idSpecification(userParam.getId()));
		if(checkIsCurrentUser(userParam)){
			result.addProperty("backValue", "不能删除自己的账号！");
			return result.toString();
		}
		
		if(StringUtils.equals(user.getUserCode(), Constants.FIXED_USER_CODE_FOR_ADMIN)){
			result.addProperty("backValue", "不能删除超级管理员admin的账号！");
			return result.toString();
		}
		
		userRepository.delete(Arrays.asList(user));
		result.addProperty("backValue", true);
		userLogService.save(UserLogOpt.MaintenanceUser, null, String.format("删除 了用户“%s”", user.getUserCode()));
		return result.toString();
	}

	/**
	 * 获取当前登录的用户信息
	 * 
	 * @return 类型:String 返回当前登录的用户信息
	 */
	@RequestMapping(value = "/search/getCurrentUserInfo", produces = "application/json")
	public String getCurrentUserInfo() {
		JsonObject jo = new JsonObject();
		User user = userSessionService.getCurrentAuthenticatedUser();
		if (user == null) {
			jo.addProperty("errorCode", "USER_NO_LOGIN");
			return jo.toString();
		}

		if (userRepository.countByUserCodeAndRole_Id(user.getUserCode(), Constants.FIXED_ROLE_ID_FOR_ADMIN) > 0 || StringUtils.equals(user.getRoleId(), Constants.FIXED_ROLE_ID_FOR_IF_ADMIN)) {
			jo.addProperty("isAdminOrOther", "admin");
		} else {
			jo.addProperty("isAdminOrOther", "Other");
		}

		jo.addProperty("userCode", user.getUserCode());
		jo.addProperty("userName", user.getUserName());
		if(user.getRole() != null){
			jo.addProperty("roleName", user.getRole().getRoleName());
		}
		jo.addProperty("companyName", user.getOrganization().getParent().getOrgName());
		jo.addProperty("deptName", user.getOrganization().getOrgName());
		jo.addProperty("empNo", user.getEmpNo());
		jo.addProperty("phoneNumber", user.getPhoneNumber());
		jo.addProperty("emailAddress", user.getEmailAddress());

		return jo.toString();
	}

	/**
	 * 获取用户的所属系统
	 * @param id 类型:String 要获取系统的用户ID
	 * @return 类型:String 用户的所属系统数据
	 */
	@RequestMapping(value = "search/getFieldSystemRoot", produces = "application/json")
	@RequiresPermissions(value = { "userManagement" })
	public String getFieldSystemRoot(String id) {
		JsonArray json = new JsonArray();
		User user = userRepository.findOne(User.idSpecification(id));
		if (!CollectionUtils.isEmpty(user.getFieldSystems())) {
			for (FieldSystem fieldSystem : user.getFieldSystems()) {
				JsonObject result = new JsonObject();
				result.addProperty("fieldSystemId", fieldSystem.getId());
				result.addProperty("fieldName", fieldSystem.getField().getName());
				result.addProperty("fieldSystemName", fieldSystem.getName());
				json.add(result);
			}
		}

		return json.toString();

	}

	/**
	 * 组织结构的展现
	 * 
	 * @param parentId
	 *            类型:String 组织结构的父节点编号
	 * @param level
	 *            类型:int 组织结构的层级
	 * @return 类型:String 返回的组织结构结构
	 * @throws ParseException 
	 */
	@RequestMapping(value = "/search/showOrganizations", produces = "application/json")
	public String showOrganizations(String parentId, int level) throws ParseException {
		Gson gson = new Gson(); 
		String org = "";
		 
		if (parentId != null) {
			List<Organization> organization = organizationRepository.findByParent_Id(parentId);
			if (organization != null) {
				org = gson.toJson(organization);
			}
		} else {
			List<Organization> organization = organizationRepository.findByLevel(level);
			List <Organization> organizations = new ArrayList<Organization>();
			if(level == 1){
				for (Organization organization2 : organization) {
					if("联友科技".equals(organization2.getOrgName())){
						organizations.add(organization2);
					}
				}
				for (Organization organization3 : organization) {
					if (!"联友科技".equals(organization3.getOrgName())) {
						organizations.add(organization3);
					}
				}
				if (!organizations.isEmpty()) {
					org = gson.toJson(organizations);
				}
			}else{
				if (!organization.isEmpty()) {
					org = gson.toJson(organization);
				}
			}
		}
		return org;
	}
	
	/**
	 * 根据用户名称查询角色名称
	 * @param username
	 * @return
	 */
	@RequestMapping("/roleNameUI")
    @ResponseBody
	public Object roleNameUI(String username) {
		 User user = new User();
		 String roleName = "";
		if(!"".equals(username)&& username !=null  ){
			 user = userRepository.findByUserCode(username);
			 roleName = user.getRole().getRoleName();
		}
		return new  ResponseBean("200","ok",roleName); 
	}
}